import React, { useState, useEffect } from "react";
import { Button, Input, message, Space, InputNumber, Tooltip } from "antd";
import {
  CopyOutlined,
  DeleteOutlined,
  SwapOutlined,
  DownloadOutlined,
} from "@ant-design/icons";
import { copyToClipboard } from "@/utils/clipboard";
import ToolTitle from "@/components/ToolTitle";
import { textToolsData } from "@/components/ToolsData";

const { TextArea } = Input;

const Px2Rem: React.FC = () => {
  const [inputText, setInputText] = useState<string>("");
  const [outputText, setOutputText] = useState<string>("");
  const [rootFontSize, setRootFontSize] = useState<number>(16);

  // px转rem的转换函数
  const convertPxToRem = (cssText: string, rootSize: number): string => {
    if (!cssText.trim()) return "";

    // 匹配所有px值，包括小数
    const pxRegex = /(\d*\.?\d+)px/g;

    return cssText.replace(pxRegex, (_match, value) => {
      const pxValue = parseFloat(value);
      const remValue = pxValue / rootSize;
      // 保留4位小数并去除多余的0
      return `${parseFloat(remValue.toFixed(4))}rem`;
    });
  };

  // 实时转换
  useEffect(() => {
    const result = convertPxToRem(inputText, rootFontSize);
    setOutputText(result);
  }, [inputText, rootFontSize]);

  const handleConvert = () => {
    if (inputText.trim() === "") {
      message.warning("请输入CSS内容");
      return;
    }

    const result = convertPxToRem(inputText, rootFontSize);
    setOutputText(result);

    if (result === inputText) {
      message.info("未发现需要转换的px值");
    } else {
      message.success("转换成功");
    }
  };

  const handleCopy = () => {
    if (!outputText) {
      message.warning("没有内容可复制");
      return;
    }

    copyToClipboard(outputText);
    message.success("已复制到剪贴板");
  };

  const handleClear = () => {
    setInputText("");
    setOutputText("");
    message.info("已清空");
  };

  const handleSwap = () => {
    if (!inputText && !outputText) {
      message.warning("没有内容可交换");
      return;
    }

    const temp = inputText;
    setInputText(outputText);
    setOutputText(temp);
    message.success("内容已交换");
  };

  const handleDownload = () => {
    if (!outputText) {
      message.warning("没有内容可下载");
      return;
    }

    try {
      const blob = new Blob([outputText], { type: "text/css" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `converted-${new Date().getTime()}.css`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      message.success("下载成功");
    } catch (error) {
      console.error("下载失败:", error);
      message.error("下载失败");
    }
  };

  const exampleCSS = `.container {
  width: 320px;
  height: 240px;
  margin: 16px auto;
  padding: 20px 24px;
  font-size: 14px;
  line-height: 20px;
  border-radius: 8px;
  border: 1px solid #ccc;
}

.button {
  width: 100px;
  height: 36px;
  padding: 8px 16px;
  margin-right: 12px;
  font-size: 14px;
}`;

  const loadExample = () => {
    setInputText(exampleCSS);
    message.success("已加载示例代码");
  };

  return (
    <div className="p-6">
      <ToolTitle
        title={
          textToolsData.find((item) => item.title === "px转rem")?.title || ""
        }
        description={
          textToolsData.find((item) => item.title === "px转rem")?.description ||
          ""
        }
      />

      <div className="grid md:grid-cols-2 gap-6 h-[calc(100vh-180px)]">
        {/* 输入区域 */}
        <div className="flex flex-col h-full">
          <div className="flex justify-between items-center mb-4">
            <span className="font-medium text-base">输入CSS代码:</span>
            <div className="flex items-center gap-4">
              <div className="flex items-center gap-2">
                <span className="text-sm">基准字体大小:</span>
                <Tooltip title="通常为16px，即1rem = 16px">
                  <InputNumber
                    value={rootFontSize}
                    onChange={(value) => setRootFontSize(value || 16)}
                    min={1}
                    max={100}
                    step={0.1}
                    addonAfter="px"
                    className="w-20"
                    size="middle"
                  />
                </Tooltip>
              </div>
              <Button type="link" onClick={loadExample} size="small">
                加载示例
              </Button>
            </div>
          </div>
          <TextArea
            value={inputText}
            onChange={(e) => setInputText(e.target.value)}
            placeholder="请在此输入包含px单位的CSS代码...&#10;&#10;例如：&#10;.container {&#10;  width: 320px;&#10;  padding: 16px;&#10;  font-size: 14px;&#10;}"
            className="w-full flex-1"
            style={{
              fontFamily: "monospace",
              height: "100%",
              resize: "none",
            }}
          />
        </div>

        {/* 输出区域 */}
        <div className="flex flex-col h-full">
          <div className="flex justify-between items-center mb-4">
            <span className="font-medium text-base">转换结果:</span>
            <Space>
              <Button type="primary" onClick={handleConvert}>
                转换
              </Button>
              <Button icon={<SwapOutlined />} onClick={handleSwap}>
                交换
              </Button>
              <Button
                icon={<DownloadOutlined />}
                onClick={handleDownload}
                disabled={!outputText}
              >
                下载
              </Button>
              <Button
                icon={<CopyOutlined />}
                onClick={handleCopy}
                disabled={!outputText}
              >
                复制
              </Button>
              <Button icon={<DeleteOutlined />} onClick={handleClear}>
                清空
              </Button>
            </Space>
          </div>
          <TextArea
            value={outputText}
            readOnly
            className="w-full h-full flex-1"
            style={{
              fontFamily: "monospace",
              height: "100%",
              resize: "none",
              backgroundColor: "#f8f9fa",
            }}
            placeholder="转换后的CSS代码将在这里显示..."
          />
        </div>
      </div>

      <div className="mt-6 text-gray-500 text-sm">
        <p>使用提示:</p>
        <ul className="list-disc pl-5">
          <li>输入包含px单位的CSS代码，系统会自动实时转换为rem单位</li>
          <li>
            可以调整基准字体大小（默认16px），转换比例 = px值 ÷ 基准字体大小
          </li>
          <li>支持小数px值的转换，结果保留4位小数并自动去除多余的0</li>
          <li>使用"交换"按钮可以将输入和输出内容互换</li>
          <li>转换结果可以复制到剪贴板或下载为CSS文件</li>
        </ul>
      </div>
    </div>
  );
};

export default Px2Rem;
